[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 镜像名称
$IMAGE_NAME = "镜像名称"
# 镜像版本
$IMAGE_TAG = "镜像版本"
$FULL_IMAGE_NAME = "$IMAGE_NAME`:$IMAGE_TAG"
# 服务器登录名称@服务器ip
$REMOTE_SERVER = "服务器登录名称@服务器ip"
$REMOTE_PORT = 22
# 远程容器名称
$REMOTE_CONTAINER_NAME = "容器名称"
# 服务器登录秘钥地址 示例: C:\Users\Administrator\.ssh\private_key
$SshKeyPath = "服务器登录秘钥地址" 
# 容器端口
$CONTAINER_PORT = 80
# 主机端口
$HOST_PORT = 80
$IMAGE_FILE = "$IMAGE_NAME-$IMAGE_TAG.tar"

# 检查Docker
Write-Host "Checking Docker..."
docker --version
if ($LASTEXITCODE -ne 0) {
    Write-Error "Docker not found"
    exit 1
}

# 检查SSH密钥文件是否存在
if (-not (Test-Path $SshKeyPath)) {
    Write-Host "ERROR: SSH key file not found: $SshKeyPath" -ForegroundColor Red
    Write-Host "Please ensure the SSH key file exists and try again." -ForegroundColor Red
    exit 1
}

# 停止本地容器
Write-Host "Cleaning local containers..."
docker stop $REMOTE_CONTAINER_NAME 2>&1 | Out-Null
docker rm $REMOTE_CONTAINER_NAME 2>&1 | Out-Null

# 检查本地镜像是否存在
Write-Host "Checking if local image exists: $FULL_IMAGE_NAME"
$localImageExists = $false
try {
    docker image inspect $FULL_IMAGE_NAME 2>&1 | Out-Null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Local image already exists, skipping build." -ForegroundColor Green
        $localImageExists = $true
    } else {
        Write-Host "Local image not found, building new image." -ForegroundColor Yellow
    }
} catch {
    Write-Host "Local image not found, building new image." -ForegroundColor Yellow
}

# 如果本地镜像不存在，则构建镜像
if (-not $localImageExists) {
    Write-Host "Building Docker image: $FULL_IMAGE_NAME"
    docker build -t $FULL_IMAGE_NAME -f "./Dockerfile" "."
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Build failed"
        exit 1
    }
}

# 检查是否已存在导出的镜像文件
if (Test-Path $IMAGE_FILE) {
    Write-Host "Image file already exists locally, skipping export." -ForegroundColor Green
} else {
    # 导出镜像
    Write-Host "Exporting image to: $IMAGE_FILE"
    docker save -o $IMAGE_FILE $FULL_IMAGE_NAME
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Export failed"
        # 尝试提供更多错误信息
        Write-Host "Troubleshooting tips:" -ForegroundColor Yellow
        Write-Host "1. Check if the image exists: docker images | grep '$IMAGE_NAME'" -ForegroundColor Yellow
        Write-Host "2. Try pulling the image again if needed" -ForegroundColor Yellow
        exit 1
    }
}

# 检查远程服务器上是否已存在镜像文件
Write-Host "Checking if image file already exists on remote server..."
$remoteFileExists = $false
try {
    $result = ssh -i $SshKeyPath -p $REMOTE_PORT $REMOTE_SERVER "test -f '/tmp/$IMAGE_FILE' && echo 'EXISTS' || echo 'NOT_EXISTS'"
    if ($result -eq "EXISTS") {
        Write-Host "Image file already exists on remote server, skipping transfer." -ForegroundColor Green
        $remoteFileExists = $true
    } else {
        Write-Host "Image file not found on remote server, will transfer." -ForegroundColor Yellow
    }
} catch {
    Write-Host "Failed to check remote file status, will attempt transfer." -ForegroundColor Yellow
}

# 如果远程文件不存在，则传输
if (-not $remoteFileExists) {
    Write-Host "Transferring to server..."
    scp -i $SshKeyPath -P $REMOTE_PORT $IMAGE_FILE "${REMOTE_SERVER}:/tmp/"
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Transfer failed"
        exit 1
    }
}

# 清理本地文件（可选）
Write-Host "Cleaning up local image file..."
Remove-Item $IMAGE_FILE -ErrorAction SilentlyContinue

$commands = @(
    "echo '=== Starting deployment ==='",
    "ls -la '/tmp/$IMAGE_FILE'",
    "docker load -i '/tmp/$IMAGE_FILE'",
    "docker stop $REMOTE_CONTAINER_NAME 2>/dev/null || echo 'No container to stop'",
    "docker rm $REMOTE_CONTAINER_NAME 2>/dev/null || echo 'No container to remove'",
    "docker run -d --name $REMOTE_CONTAINER_NAME -p ${HOST_PORT}:${CONTAINER_PORT} $FULL_IMAGE_NAME",
    "docker ps -f name=$REMOTE_CONTAINER_NAME",
    "sleep 10",
    "docker logs $REMOTE_CONTAINER_NAME --tail 10",
    "echo '=== Cleaning up ==='",
    "rm -f '/tmp/$IMAGE_FILE'",
    "docker system prune -af",
    "echo '=== Deployment completed ==='"
)

# 逐条执行命令
foreach ($cmd in $commands) {
    Write-Host "Executing: $cmd" -ForegroundColor Yellow
    try {
        $result = ssh -i $SshKeyPath -p $REMOTE_PORT $REMOTE_SERVER $cmd 2>&1
        Write-Host $result
    } catch {
        Write-Host "Error executing command: $cmd" -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Red
    }
    
    # 如果命令失败且不是echo/rm/docker stop/docker rm命令，则停止执行
    if ($LASTEXITCODE -ne 0 -and 
        $cmd -notlike "*echo*" -and 
        $cmd -notlike "*docker stop*" -and 
        $cmd -notlike "*docker rm*" -and
        $cmd -notlike "*rm -f*") {
        Write-Host "ERROR: Command failed: $cmd" -ForegroundColor Red
        Write-Host "Deployment failed at step: $cmd" -ForegroundColor Red
        exit 1
    }
}

Write-Host "`n=== Deployment Successful! ===" -ForegroundColor Green
$serverIp = $REMOTE_SERVER -replace ".*@", ""
Write-Host "Access URL: http://${serverIp}:80" -ForegroundColor Cyan